package com.jxwifi.cloud.quickcleanserver.welcome;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.basicactivity.BasicActivity;
import com.bumptech.glide.Glide;
import com.jxwifi.cloud.quickcleanserver.MainActivity;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.popwindow.PopProtocol;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2019/5/15.
 */

public class WelcomeActivity extends CleanBasicActivity {

    private final int SDK_PERMISSION_REQUEST = 127;
    private static final int SPLASH_DIPLAY_LENGHT = 1500;
    @Bind(R.id.welcome_images)
    ImageView mWelComeImages;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //下面的这个判断是用来解决应用程序在第一次安装成功点击打开后，再点击home键回到桌面后再点击程序出现重新启动的问题
        // （还需要注意的一点是在onDestroy方法中不能写finsh()和System.exit(0)方法要不然程序或出现短时间的黑屏）
        if((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0){
            finish();
            return;
        }
        setContentView(R.layout.activity_welome);
        ButterKnife.bind(this);
        initHeadLayout();
        getPersimmions();
    }

    /**
     * 初始化浸入式标题
     */
    private void initHeadLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    private void jump() {
        Intent intent = new Intent();
        intent.setClass(mBaseContext,MainActivity.class);
        intent.putExtra("mainindex", "0");
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);//处理广告页中的启动动画，添加这个可以去掉系统的默认加载动画
        finish();
    }

    private void firstRun() {
        sharedPreferences = getSharedPreferences("FirstRun",0);
        Boolean first_run = sharedPreferences.getBoolean("First",true);
        if (first_run){
            //Toast.makeText(this,"第一次",Toast.LENGTH_LONG).show();
            protocol();
        }
        else {
            //Toast.makeText(this,"不是第一次",Toast.LENGTH_LONG).show();
            jump();
            //protocol();
        }
    }

    public void protocol(){
        PopProtocol mDodule=new PopProtocol(mBaseContext, new PopProtocol.PopProtocolListener() {
            @Override
            public void PopDisagree() {
                Glide.get(mBaseContext).clearMemory();
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(EXITAPP));
                System.gc();
            }

            @Override
            public void PopAgree() {
                sharedPreferences.edit().putBoolean("First",false).commit();
                jump();
            }
        });
        Popwindows popwindow = PopWindowUtil.getPopupWindow(mDodule.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.MATCH_PARENT);
        mDodule.setPopwindow(popwindow);
        popwindow.show(mWelComeImages, Popwindows.Location.BOTTOM);
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             * 其他需要到很重要的限制在此处都要申请
             */
            // 定位精确位置*
            if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (checkSelfPermission(android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.CAMERA);
            }
            // 读写权限
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        firstRun();
                    }
                }, SPLASH_DIPLAY_LENGHT);
            }
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    firstRun();
                }
            }, SPLASH_DIPLAY_LENGHT);
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                firstRun();
            }
        }, SPLASH_DIPLAY_LENGHT);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);//处理广告页中的启动动画，添加这个可以去掉系统的默认加载动画
    }
}
